package com.dykj.fireFighting.common.core.utils;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @Description
 * @date: 2019-12-19 13:18
 */
public class DownLoadFileUtils {


    public static void downloadFile(String fileName, InputStream inputStream, HttpServletRequest request, HttpServletResponse response)  {
      try {
          //处理中文文件名码
          if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                  request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                  || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
              fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
          } else {
              //非IE浏览器的处理：
              fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
          }

          response.setHeader("Pragma", "No-cache");
          response.setHeader("Cache-Control", "No-cache");
          response.setDateHeader("Expires", 0);
          // 通知浏览器进行文件下载
          response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
          IOUtils.copy(inputStream, response.getOutputStream());
      }catch (Exception e){
          e.printStackTrace();
      }
    }
}
